<template>
  <rx-layout>
    <div slot="center" style>
      <rx-fit>
        <div slot="toolheader" foldheader="true" foldbtn="false" border="false">
          <div class="table-operator">
              <a-button type="primary" icon="plus" @click="addApi">
                  {{$ti18('rxList.newBtn','新建')}}
              </a-button>
          </div>
          <span class="search-btn-box">
                <span class="search-btn" @click="searchshow"><i class="iconfont iconguolv"></i>
                {{$ti18('rxList.leachBtn','过滤')}}
                </span>
           </span>
        </div>
        <div slot="searchbar" btnalign="right"  v-if="fitSearch" @search="search" @cancel="cancel" @close="close">
          <a-form layout="vertical">
                <a-form-item :label="i18n('form.apiName','接口名称')">
                    <a-input :placeholder="i18n('form.apiName','接口名称','input')" v-model="queryParam.Q_API_NAME__S_LK"/>
                </a-form-item>
                <a-form-item :label="i18n('form.status','状态')">
                    <a-select style="width: 100%" :placeholder="i18n('form.status','状态','input')" v-model="queryParam.Q_STATUS__S_LK">
                        <a-select-option value="">
                            {{i18n('isProjectStatusMap.select','请选择')}}
                        </a-select-option>
                        <a-select-option value="DONE">
                            {{i18n('isProjectStatusMap.enable','启用')}}
                        </a-select-option>
                        <a-select-option value="UNDONE">
                            {{i18n('isProjectStatusMap.disable','禁用')}}
                        </a-select-option>
                    </a-select>
                </a-form-item>
          </a-form>
        </div>
        <rx-grid
                ref="table"
                :allowRowSelect="false"
                :multiSelect="true"
                :columns="columns"
                :defaultPageSize="10"
                :loadDataOnstart="false"
                url="/api-system/system/core/sysInterfaceApi/query"
                :queryParam="queryParam"
                data-field="result.data"
                :pageSizeOptions="['10','30','40']"
                id-field="apiId"
                @selectChange="onSelectChange"
        >
            <span slot="apiName" slot-scope="{ text, record }">
                <a @click="onSelect(record)">{{text}}</a>
            </span>
            <span slot="apiPath" slot-scope="{ text, record }">
                <a-tag :color="methodMap[record.apiType=='SOAP'?record.apiType:record.apiMethod].color">
              <span>{{ methodMap[record.apiType=='SOAP'?record.apiType:record.apiMethod].text }}</span>
            </a-tag>
                {{text}}
            </span>
            <span slot="classificationId" slot-scope="{ text, record }">
                <a-dropdown>
                    <a class="ant-dropdown-link">
                      {{classificationOptions[text]}} <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                      <a-menu-item v-for="(classificationName,classificationId) in classificationOptions">
                        <a @click="changeClassification(record,classificationId)">{{classificationName}}</a>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
            </span>
            <span slot="status" slot-scope="{ text, record }">
                <a-dropdown>
                    <a class="ant-dropdown-link">
                      <a-tag :color="statusMap[text].color">
                          <span>{{ statusMap[text].text }}</span>
                      </a-tag>
                      <a-icon type="down" />
                    </a>
                    <a-menu slot="overlay">
                      <a-menu-item>
                        <a @click="changeStatus(record,'DONE')">
                            {{i18n('isProjectStatusMap.enable','启用')}}
                        </a>
                      </a-menu-item>
                      <a-menu-item>
                        <a @click="changeStatus(record,'UNDONE')">
                            {{i18n('isProjectStatusMap.disable','禁用')}}
                        </a>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
          </span>
        </rx-grid>
      </rx-fit>
    </div>
  </rx-layout>
</template>

<script>
  import SysInterfaceApiApi from '@/api/system/core/sysInterfaceApi'
  import SysInterfaceApiAdd from "./SysInterfaceApiAdd";
  import SysInterfaceApiEdit from './SysInterfaceApiEdit'
  import {BaseList,RxFit,RxGrid,Util } from "@lowcode/jpaas-common-lib";
  import {      mapState,      mapMutations  } from 'vuex';

  export default {
    name: 'SysInterfaceApiList',
    mixins: [BaseList],
    components: {
      RxGrid,
      RxFit
    },
    props:["projectId","classificationId","classifications"],
      computed:{
          ...mapState({
              navigation: state => state.appSetting.navigation,
              frontType: state => state.appSetting.frontType,
          })
      },
    created() {
       this.needFilterAppId();
    },
    mounted(){
       this.loadByParams({Q_PROJECT_ID__S_EQ:this.projectId,Q_CLASSIFICATION_ID__S_LK: this.classificationId});
    },
    data() {
      return {
          columns: [
              {
                  title: '#',
                  type: 'indexColumn',
                  width: 60,
                  dataIndex: 'serial',
                  scopedSlots: {customRender: 'serial'}
              },
              {title: this.i18n('form.apiName','接口名称'), dataIndex: 'apiName', width: 120, scopedSlots: {customRender: 'apiName'}},
              {title:  this.i18n('form.interfacePath','接口路径'), dataIndex: 'apiPath', width: 140, scopedSlots: {customRender: 'apiPath'}},
              {title:  this.i18n('form.interfaceClassification','接口分类'), dataIndex: 'classificationId', width: 80, scopedSlots: {customRender: 'classificationId'}},
              {title: this.i18n('form.status','状态'), dataIndex: 'status', width: 60, scopedSlots: {customRender: 'status'}}
          ],
          component: SysInterfaceApiEdit,
          comment: this.i18n('list.comment','接口API表'),
          widthHeight: ['800px', '400px'],
          fitSearch: false,
          classificationOptions:{},
          statusMap: {
              'DONE': {color: 'green', text: this.i18n('isProjectStatusMap.enable','启用')},
              'UNDONE': {color: 'red', text: this.i18n('isProjectStatusMap.disable','禁用')}
          },
          methodMap:{
              'SOAP':{color:'yellow', text: 'SOAP'},
              'GET': {color: 'green', text: 'GET'},
              'POST': {color: 'blue', text: 'POST'},
              'PUT': {color: 'orange', text: 'PUT'},
              'DELETE': {color: 'red', text: 'DELETE'}
          }
      }
    },

    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "sysInterfaceProject", key);
        },
        delById(ids) {
            return SysInterfaceApiApi.del({ids: ids.join(',')});
        },
        getListByParams(parameter) {
            return SysInterfaceApiApi.query(parameter)
        },
        search() {
            this.$refs.table.loadData()
        },
        cancel() {
            this.resetSearch();
        },
        close() {
            //关闭按钮
            this.fitSearch = false;
        },
        loadByParams(params) {
            this.loadClassification();
            this.$refs.table.loadByParams(params);
        },
        addApi(){
            var conf = {
                component: SysInterfaceApiAdd,
                title: this.$ti18('rxList.newBtn','添加') + "-" + this.comment,
                urlType: 'Add',
                data:{projectId:this.projectId,classificationId:this.classificationId}
            };
            this.handleEdit(conf);
        },
        onSelect(record){
            this.$bus.$emit("apiFormLoadEvent",record.apiId,record.classificationId);
        },
        handleEdit(conf) {
            var self_ = this;
            let _showType = this.showType ;
            var _pkId = conf.pkId;
            if(_showType != "newPage"){//弹窗模式打开 ;
                var baseConf = {
                    "curVm": self_,
                    "data": {"pkId": _pkId}
                };
                let config = Object.assign(baseConf, conf);
                if (!this.widthHeight) {
                    config.max = true;
                } else {
                    config.widthHeight = this.widthHeight
                }
                Util.open(config, function (action) {
                    if (action == "ok") {
                        self_.refreshGrid();
                        var apiId=this.resultData.apiId;
                        var classificationId = this.resultData.classificationId;
                        self_.$bus.$emit("apiLoadEvent");
                        this.$bus.$emit("apiFormLoadEvent",apiId,classificationId);
                    }
                });
            }else {
                let _key  = conf.component.name + conf.urlType ;
                let _path = conf.component.__source || conf.component.__file ;
                _path = _path.replace('src/views/','');
                let obj = {
                    component:_path,//组件路径
                    props:{
                        pkId:conf.pkId,
                        urlTypeKey:_key
                    },
                    key: _key,
                    title:conf.title,
                    cmptKey:_key + new Date().getTime()
                }
                this.setActiveKey(obj.key);
                let _isObj = this.navigation[this.frontType].findIndex(item => {return item.key == obj.key && item.title == obj.title });
                if(_isObj == -1){
                    this.navigation[this.frontType].push(obj);
                }else {
                    //存在的情况下，替换；
                    let _idx = null ;
                    let _navArr = this.navigation[this.frontType].concat();
                    for (let i in _navArr){
                        if(_navArr[i].key == obj.key){
                            _idx = i ;
                        }
                    }
                    _navArr[_idx] = obj ;
                }
                this.$bus.$off(_key).on(_key,(action)=>{
                    if (action == "ok") {
                        self_.refreshGrid();
                    }
                });
            }
        },
        loadClassification() {
            for (var i = 0; i < this.classifications.length; i++) {
                var obj = this.classifications[i];
                this.classificationOptions[obj.classificationId] = obj.classificationName;
            }
        },
        changeStatus(record,curStatus){
            if(record.status==curStatus){
                return;
            }
            var self_=this;
            SysInterfaceApiApi.save({pkId:record.apiId,status:curStatus}).then(res=>{
                if (res.success && res.code == 200) {
                    self_.refreshGrid();
                }
            })
        },
        changeClassification(record,curClassificationId){
            if(record.classificationId==curClassificationId){
                return;
            }
            var self_=this;
            SysInterfaceApiApi.save({pkId:record.apiId,classificationId:curClassificationId}).then(res=>{
                if (res.success && res.code == 200) {
                    self_.refreshGrid();
                    self_.$bus.$emit("apiLoadEvent");
                }
            })
        }
    },
    watch:{
        classificationId:{
            handler:function (val) {
                this.loadByParams({Q_PROJECT_ID__S_EQ:this.projectId,Q_CLASSIFICATION_ID__S_LK: val});
            }
        }
    }
  }
</script>
<style scoped>

</style>

